package com.it.you.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ExecutorDemo {

    /**
     * 最大线程数
     */
    private static final int MAX_THREAD_NUM = 20;

    /**
     * 创建线程池执行器
     * @param operNum 操作数
     * @return
     */
    public static ExecutorService createThreadPoolExecutor(int operNum) {
        int nThreads = Math.min(operNum, MAX_THREAD_NUM);
        nThreads = Math.max(nThreads, 1);
        return Executors.newFixedThreadPool(nThreads);
    }

    /**
     * 执行线程
     * @param executor 线程池执行器
     * @param runnable
     */
    public static void execute(ExecutorService executor, Runnable runnable) {
        executor.execute(runnable);
    }

    /**
     * 关闭线程池执行器
     * @param executor 线程池执行器
     * @param timeout 超时毫秒数
     */
    public static void shutdown(ExecutorService executor, long timeout) {
        executor.shutdown();
        try {
            log.info("主线程等待子线程执行...");
            boolean isFinish = executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
            log.info("主线程结束等待");
            if (isFinish) {
                log.info("子线程全部执行完毕");
            } else {
                // 关闭
                executor.shutdownNow();
                throw new RuntimeException("子线程执行超时");
            }
        } catch (InterruptedException e) {
            log.error("主线程等待子线程执行失败：{}{}", e.getMessage(), e);
            executor.shutdownNow();
        }
    }

}
